package com.dl.test.util;

import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.select.FromItem;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;

/**
 * @author DL
 * @create 2022-08-30 11:13
 */
@Slf4j
public class SqlUtil {

    public static String appendWhere(Select selectStatement, String whereSql) throws JSQLParserException {
        if (whereSql == null || whereSql.length() == 0) {
            throw new RuntimeException();
        }
        whereSql = whereSql.toUpperCase();
        if (whereSql.startsWith("WHERE")){
            whereSql = whereSql.substring(5);
        }
        log.info("whereSql:{}", whereSql);
        StringBuilder whereBuilder = new StringBuilder(whereSql);
        Expression expression = CCJSqlParserUtil.parseCondExpression(whereBuilder.toString());

        PlainSelect plain = (PlainSelect) selectStatement.getSelectBody();
        log.info("plain:{}", plain);

        FromItem fromItem = plain.getFromItem();
        log.info("fromItem:{}", fromItem);
        log.info("getAlias:{}", fromItem.getAlias());

        //增加sql语句的逻辑部分处理
        if (fromItem.getAlias() != null) {
            whereBuilder.append(fromItem.getAlias().getName()).append(whereSql);
        }
        Expression where = plain.getWhere();
        log.info("where:{}", where);
        if (where == null) {
            plain.setWhere(expression);
        } else {
            System.out.println("where条件之前存在，需要重新进行拼接");
            //where条件之前存在，需要重新进行拼接
            whereBuilder.append(where).append(" and ").append(whereBuilder);
            plain.setWhere(expression);
        }
        return selectStatement.toString();
    }
}
